using JNPF.Basics.Models;
using JNPF.Data;
using JNPF.Data.Util;
using JNPF.Utils;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 聊天内容
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2019-07-24
    /// </summary>
    internal class IMContentService : DataFactory, IMContentIService
    {
        /// <summary>
        /// 获取消息列表
        /// </summary>
        /// <param name="input">分页参数</param>
        /// <param name="sendUserId">发送者</param>
        /// <param name="receiveUserId">接收者</param>
        /// <returns></returns>
        public async Task<PageResult<IMContentEntity>> GetMessageList(string sendUserId, string receiveUserId, PageInput input)
        {
            using (var db = this.Basic)
            {
                var whereLambda = ExtLinq.True<IMContentEntity>();
                //发件人、收件人
                if (!string.IsNullOrEmpty(sendUserId) && !string.IsNullOrEmpty(receiveUserId))
                {
                    whereLambda = whereLambda.And(m => m.SendUserId == sendUserId || m.SendUserId == receiveUserId);
                    whereLambda = whereLambda.And(m => m.ReceiveUserId == sendUserId || m.ReceiveUserId == receiveUserId);
                }
                //关键字查询
                if (input != null && !string.IsNullOrEmpty(input.keyword))
                {
                    whereLambda = whereLambda.And(m => m.Content.Contains(input.keyword));
                }
                input.sidx = "SendTime";
                return await db.GetIQueryable<IMContentEntity>().Where(whereLambda).GetPageResultAsync(input);

            }
        }
        /// <summary>
        /// 获取未读列表
        /// </summary>
        /// <param name="receiveUserId">接收者</param>
        /// <returns></returns>
        public async Task<List<IMUnreadNumModel>> GetUnreadList(string receiveUserId)
        {
            using (var db = this.Basic)
            {
                var parameters = new List<DbParameter>();
                var dbSql = new StringBuilder();
                dbSql.Append(@"SELECT * FROM (SELECT SUM(CASE WHEN F_State = 0 THEN 1 ELSE 0 END) AS UnreadNum, F_SendUserId AS SendUserId, F_ReceiveUserId AS ReceiveUserId
	                           FROM Base_IMContent WHERE 1 = 1 AND F_ReceiveUserId = @receiveUserId GROUP BY F_SendUserId, F_ReceiveUserId ) t WHERE UnreadNum > 0");
                parameters.Add(DataHelper.CreateParameter("@receiveUserId", receiveUserId));
                var list = await db.GetListSqlAsync<IMUnreadNumModel>(dbSql.ToString(), parameters.ToArray());
                var list1 = await db.GetListSqlAsync<IMUnreadNumModel>("select F_SendUserId AS SendUserId, F_Content AS DefaultMessage,F_ContentType AS DefaultMessageType, F_SendTime AS DefaultMessageTime from Base_IMContent WHERE 1 = 1 AND F_ReceiveUserId = @receiveUserId AND F_State = 0 order by F_SendTime desc", parameters.ToArray());
                foreach (var item in list)
                {
                    var defaultItem = list1.FirstOrDefault(q => q.sendUserId == item.sendUserId);
                    item.defaultMessage = defaultItem.defaultMessage;
                    item.defaultMessageType = defaultItem.defaultMessageType;
                    item.defaultMessageTime = defaultItem.defaultMessageTime;
                }
                return list;
            }
        }
        /// <summary>
        /// 获取未读消息
        /// </summary>
        /// <param name="receiveUserId">接收者</param>
        /// <returns></returns>
        public async Task<int> GetUnreadCount(string receiveUserId)
        {
            using (var db = this.Basic)
            {
                return await db.GetCountAsync<IMContentEntity>(m => m.ReceiveUserId == receiveUserId && m.State == 0);
            }
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="sendUserId">发送者</param>
        /// <param name="receiveUserId">接收者</param>
        /// <param name="message">消息内容</param>
        /// <param name="messageType">消息类型</param>
        /// <returns></returns>
        public async Task<int> SendMessage(string sendUserId, string receiveUserId, string message, string messageType)
        {
            using (var db = this.Basic)
            {
                IMContentEntity entity = new IMContentEntity();
                entity.Id = CommonHelper.Guid;
                entity.SendUserId = sendUserId;
                entity.SendTime = DateTime.Now;
                entity.ReceiveUserId = receiveUserId;
                entity.State = 0;
                entity.Content = message;
                entity.ContentType = messageType;
                return await db.InsertAsync(entity);
            }
        }
        /// <summary>
        /// 设置已读
        /// </summary>
        /// <param name="sendUserId">发送者</param>
        /// <param name="receiveUserId">接收者</param>
        public async Task<int> ReadMessage(string sendUserId, string receiveUserId)
        {
            using (var db = this.Basic)
            {
                var dbSql = new StringBuilder();
                dbSql.Append(@"UPDATE Base_IMContent SET F_State = 1, F_ReceiveTime = @receiveTime WHERE 1 = 1
	                           AND F_State = 0 AND F_SendUserId = @sendUserId AND F_ReceiveUserId = @receiveUserId");
                var parameters = new List<DbParameter>();
                parameters.Add(DataHelper.CreateParameter("@receiveTime", DateTime.Now));
                parameters.Add(DataHelper.CreateParameter("@sendUserId", sendUserId));
                parameters.Add(DataHelper.CreateParameter("@receiveUserId", receiveUserId));
                return await db.ExecuteSqlAsync(dbSql.ToString(), parameters.ToArray());
            }
        }
    }
}
